import { useEffect, useState } from 'react'
import style from './Index.module.less'

function initCanvas (setData, message, size = 1) {
  const goal = document.querySelector('#testWaterMark')
  const d = document.createElement('canvas')
  const ctx = d.getContext('2d')
  d.width = `${300 * size}`
  d.height = `${200 * size}`
  d.style = 'background-color: red;'
  goal.appendChild(d)
  ctx.rotate(30 * Math.PI / 180)
  ctx.translate(-25, -25)
  ctx.fillStyle = '#666'
  ctx.font = `${40 * size}px Georgia`
  ctx.fillText(`It's ${message}`, `${50 + 10 * size}`, `${50 + 10 * size}`)
  setData(d.toDataURL())
  goal.removeChild(d)
}

function Index ({ size }) {
  const [message, setMessage] = useState('')
  const [data, setData] = useState('')
  const [isTest, setIsTest] = useState(false)
  useEffect(() => {
    const h = window.location.host
    if (h.indexOf('zhichu.tech') !== -1) {
      setIsTest(true)
      setMessage('zhichu.tech')
    } else if (h.indexOf('localhost') === 0) {
      setIsTest(true)
      setMessage(h)
    }
  }, [])
  useEffect(() => {
    if (isTest) {
      initCanvas(setData, message, size)
    }
  }, [isTest, message, size])
  if (!isTest) {
    return <span />
  }
  return (
    <div id='testWaterMark' className={style.container} style={{ backgroundImage: `url(${data})` }} />
  )
}

export default Index
